package Connector.Processor;

import Connector.ConnectorUtils;
import Connector.Request;
import Connector.Response;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class ServletProcessor {
    URLClassLoader getServletLoader() throws MalformedURLException {

        System.out.println("ServletProcessor is creating a ClassLoader...");

        // 创建file实例
        File resource = new File(ConnectorUtils.WEB_ROOT);

        // 从file得到URL
        URL url = resource.toURI().toURL();

        System.out.println("ServletProcessor creates a ClassLoader at URI of " + ConnectorUtils.WEB_ROOT + " successfully.");

        // 通过URL创建ClassLoader
        return new URLClassLoader(new URL[] {url});
    }

    Servlet getServlet(URLClassLoader loader, Request request) throws ClassNotFoundException, InstantiationException, IllegalAccessException {

        System.out.println("ServletProcessor is creating an instance of Servlet using ClassLoader...");

        System.out.println("ServletProcessor calls Request to get URI.");

        String uri = request.getRequestURI();
        String servletName = uri.substring(uri.lastIndexOf("/") + 1);

        System.out.println("ServletProcessor get the name of Servlet: "+ servletName + " from Request.");

        // 通过反射得到servlet类
        Class servletClass = loader.loadClass(servletName);

        System.out.println("ServletProcessor calls Classloader...");

        // 通过反射创建servlet实例
        Servlet servlet = (Servlet)servletClass.newInstance();

        System.out.println("ServletProcessor creates the Servlet instance successfully.");

        return servlet;
    }


    public void process(Request request, Response response) throws MalformedURLException {    // MalformedURLException是IOException的子类，所以这里可以合并

        System.out.println("ServletProcessor is processing the Request and Response...");

        URLClassLoader loader = getServletLoader();

        try {
            Servlet servlet = getServlet(loader, request);
            servlet.service(request, response);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // TODO 为什么要try-catch? 直接throws会怎么样?
    }
}
